﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using POMain.API.Dtos;
using API.Entities;
using POMain.API.Infrastructure;
using POMain.API.ViewModel;
using System.Linq;
using System.Net;



namespace POMain.API.Controllers
{
    [Route("api/v1/[controller]")]
    [ApiController]
    public class VaccinationPointController : ControllerBase
    {

        private readonly PODbContext _context;

        public VaccinationPointController(PODbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));

            _context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }


        /// <summary>
        /// 接种站点清单
        /// </summary>
        /// <returns></returns>
        [HttpGet("all")]
        [ProducesResponseType(typeof(List<VaccinationPointDto>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<List<VaccinationPointDto>>> GetVaccinationPointsAsync()
        {
            var query = _context.VaccinationPoints
                    .Select(x => new VaccinationPointDto
                    {
                        Id = x.Id,
                        Name = x.Name,
                        Principal = x.Principal,
                        Address = x.Address,
                        Phone = x.Phone,
                    });

            var dtos = await query.ToListAsync();

            return dtos;
        }


        /// <summary>
        /// 获取分页接种站点清单
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet("paged")]
        [ProducesResponseType(typeof(PaginatedItemsViewModel<VaccinationPointDto>), (int)HttpStatusCode.OK)]
        public async Task<ActionResult<PaginatedItemsViewModel<VaccinationPointDto>>> ItemsAsync(
          string? keyword = "",
          [FromQuery] int pageSize = 10,
          [FromQuery] int pageIndex = 0)
        {

            var query = _context.VaccinationPoints.Select(x=>new VaccinationPointDto {
                Id = x.Id,
                Name =x.Name,
                Phone =x.Phone,
                Address =x.Address,
                Principal =x.Principal
            });
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = query.Where(x => x.Name.Contains(keyword) || x.Address.Contains(keyword) || x.Phone.Contains(keyword));
            }
            var totalItems = await query
              .LongCountAsync();

            var itemsOnPage = await query
                .OrderBy(x=>x.Name)
                .Skip(pageSize * pageIndex)
                .Take(pageSize)
                .ToListAsync();

            return new PaginatedItemsViewModel<VaccinationPointDto>(pageIndex, pageSize, totalItems, itemsOnPage);
        }



        /// <summary>
        /// 创建接种站点档案
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public async Task CreateAsync(VaccinationPointEditDto input)
        {
            if (!_context.VaccinationPoints.Any(x => x.Name == input.Name))
            {
                var entity = new VaccinationPoint
                {
                    Id = Guid.NewGuid(),
                    Address = input.Address,
                    Name = input.Name,
                    Phone = input.Phone,
                    Principal = input.Principal
                };

                _context.Add(entity);
                await _context.SaveChangesAsync();
            }
            else
            {
                var entity = await _context.VaccinationPoints.Where(x => x.Name == input.Name).FirstOrDefaultAsync();
                entity.Name = input.Name;
                entity.Address = input.Address;
                entity.Phone = input.Phone;
                entity.Principal = input.Principal;

                _context.Update(entity);
                await _context.SaveChangesAsync();
            }




        }

        /// <summary>
        /// 更新接种站点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task UpdateAsync(Guid id, VaccinationPointEditDto input)
        {
            var entity = await _context.VaccinationPoints.Where(x => x.Id == id).FirstOrDefaultAsync();
            if (entity == null)
            {
                entity = new VaccinationPoint
                {
                    Id = Guid.NewGuid(),
                    Address = input.Address,
                     Name =input.Name,
                      Phone =input.Phone,
                       Principal =input.Principal
                };

                _context.Add(entity);
                await _context.SaveChangesAsync();
            }
            else
            {
                entity.Name = input.Name;
                entity.Address = input.Address;
                entity.Phone = input.Phone;
                entity.Principal = input.Principal;

                _context.Update(entity);
                await _context.SaveChangesAsync();
            }


        }

        /// <summary>
        /// 删除接种站点
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete")]
        public async Task UpdateAsync(Guid id)
        {
            var entity = await _context.VaccinationPoints.Where(x => x.Id == id).FirstOrDefaultAsync();
            if (entity != null)
            {
                _context.Remove<VaccinationPoint>(entity);
                await _context.SaveChangesAsync();
            }
        }

    }
}
